<?php

namespace common\rewrites\hightman\xunsearch;

use common\Tools;
use yii\helpers\FileHelper;

class Connection extends \hightman\xunsearch\Connection
{
    public $iniDirectory;

    public $serverIp = '127.0.0.1';
    public $indexPort = 8383;
    public $searchPort = 8384;
    public $modelsNamespace = 'common\models\xunsearch';

    public function init()
    {
        parent::init();
    }

    public function generateIniFiles()
    {
        $aliasPath = '@'.str_replace('\\', '/', $this->modelsNamespace);
        $modelsDir = \Yii::getAlias($aliasPath);
        $files = FileHelper::findFiles($modelsDir, ['only' => ['*.php']]);
        $phpEol = PHP_EOL;
        foreach ($files as $k => $file) {
            $name = str_replace('.php', '', basename($file));
            $className = $this->modelsNamespace . '\\' . $name;
            $projectName = Tools::uncamelize($name);
            $reflectionClass = new \ReflectionClass($className);
            $classDocComment = $reflectionClass->getDocComment();
            $iniContent = "project.name = {$projectName}{$phpEol}project.default_charset = utf-8{$phpEol}server.index = {$this->serverIp}:{$this->indexPort}{$phpEol}server.search = {$this->serverIp}:{$this->searchPort}{$phpEol}{$phpEol}";
            $lines = preg_split('/\r\n|\r|\n/', $classDocComment);
            foreach ($lines as $k1 => $line) {
                if (strpos($line, '@property') !== false) {
                    list($x, $y) = explode('@property', $line);
                    $z = trim($y);
                    list($type, $flied, $xType) = explode(' ', $z);
                    $flied = str_replace('$', '', $flied);
                    $xType = preg_replace('/^\[(.*)\]$/', '$1', $xType);
                    $iniContent .= "[{$flied}]{$phpEol}type = {$xType}{$phpEol}{$phpEol}";
                }
            }
            $iniFileDir = \Yii::getAlias($this->iniDirectory);
            if (!is_dir($iniFileDir)) {
                FileHelper::createDirectory($iniFileDir);
            }
            $iniFileName = "{$iniFileDir}/{$projectName}.ini";
            file_put_contents($iniFileName, $iniContent);
        }
    }
}
